import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'base_page.dart';
import '../services/app_state_service.dart';
import '../services/api_service.dart';
import '../models/contact_model.dart';
import '../widgets/common_button.dart';
import '../widgets/loading_overlay.dart';

/// 客户管理页面
class ContactsPage extends BasePage {
  const ContactsPage({super.key});

  @override
  State<ContactsPage> createState() => _ContactsPageState();
}

class _ContactsPageState extends BasePageState<ContactsPage> with WidgetsBindingObserver, AutomaticKeepAliveClientMixin {
  final TextEditingController _searchController = TextEditingController();
  List<Contact> _contacts = [];
  List<Contact> _filteredContacts = [];
  bool _isSearching = false;
  bool _hasLoaded = false; // 标记是否已经加载过数据
  int _lastLoadTime = 0; // 记录上次加载时间

  @override
  bool get wantKeepAlive => true; // 保持页面状态

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // 延迟加载，确保上下文完全初始化
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadContacts();
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _searchController.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台回到前台时，重新加载数据
    // 只有在客户页面可见时才加载客户数据
    if (state == AppLifecycleState.resumed && _hasLoaded && mounted) {
      // 检查当前页面是否是客户页面
      final currentRoute = ModalRoute.of(context)?.settings.name;
      if (currentRoute == '/contacts' || currentRoute == '/contacts_page') {
        _loadContacts();
      }
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 当页面依赖发生变化时（比如从其他页面切换回来），检查是否需要重新加载
    // 只有在客户页面可见时才加载客户数据
    final currentTime = DateTime.now().millisecondsSinceEpoch;
    if (_hasLoaded && (currentTime - _lastLoadTime) > 5000 && mounted) { // 如果距离上次加载超过5秒，则重新加载
      // 检查当前页面是否是客户页面
      final currentRoute = ModalRoute.of(context)?.settings.name;
      if (currentRoute == '/contacts' || currentRoute == '/contacts_page') {
        _loadContacts();
      }
    }
  }

  /// 加载客户列表
  Future<void> _loadContacts() async {
    showLoading('加载中...');
    
    try {
      final appState = Provider.of<AppStateService>(context, listen: false);
      final userTel = appState.currentUserTel ?? '';
      
      print('=== 加载客户列表调试信息 ===');
      print('用户手机号: $userTel');
      
      final response = await ApiService.getAllContacts(userTel);
      
      print('API响应成功: ${response.isSuccess}');
      print('API响应消息: ${response.message}');
      print('API响应数据: ${response.data}');
      print('=== 调试信息结束 ===');
      
      if (response.isSuccess && response.data != null) {
        setState(() {
          _contacts = response.data!;
          _filteredContacts = List.from(_contacts);
          _hasLoaded = true; // 标记已加载
          _lastLoadTime = DateTime.now().millisecondsSinceEpoch; // 记录加载时间
        });
        // 更新应用状态
        appState.setContacts(_contacts);
        print('成功加载 ${_contacts.length} 个客户');
      } else {
        showError(response.message);
        print('加载客户列表失败: ${response.message}');
      }
    } catch (e) {
      showError('加载客户列表失败: $e');
      print('加载客户列表异常: $e');
    } finally {
      hideLoading();
    }
  }

  /// 搜索客户
  void _searchContacts(String query) {
    setState(() {
      if (query.isEmpty) {
        _filteredContacts = List.from(_contacts);
      } else {
        _filteredContacts = _contacts.where((contact) {
          return contact.name.toLowerCase().contains(query.toLowerCase()) ||
                 contact.tel.contains(query) ||
                 contact.carCode.toLowerCase().contains(query.toLowerCase());
        }).toList();
      }
    });
  }

  /// 添加客户
  void _addContact() {
    _showContactDialog();
  }

  /// 编辑客户
  void _editContact(Contact contact) {
    _showContactDialog(contact: contact);
  }

  /// 删除客户
  void _deleteContact(Contact contact) async {
    final confirmed = await showConfirmDialog(
      title: '确认删除',
      content: '确定要删除客户"${contact.name}"吗？',
    );
    
    if (confirmed == true) {
      showLoading('删除中...');
      
      try {
        final response = await ApiService.deleteContact(contact.id ?? '');
        if (response.isSuccess) {
          setState(() {
            _contacts.removeWhere((c) => c.id == contact.id);
            _filteredContacts.removeWhere((c) => c.id == contact.id);
          });
          // 更新应用状态
          if (mounted) {
            final appState = Provider.of<AppStateService>(context, listen: false);
            appState.removeContact(contact.id ?? '');
          }
          showSuccess('删除成功');
        } else {
          showError(response.message);
        }
      } catch (e) {
        showError('删除失败: $e');
      } finally {
        hideLoading();
      }
    }
  }

  /// 显示客户编辑对话框
  void _showContactDialog({Contact? contact}) {
    final isEdit = contact != null;
    final nameController = TextEditingController(text: contact?.name ?? '');
    final telController = TextEditingController(text: contact?.tel ?? '');
    final carCodeController = TextEditingController(text: contact?.carCode ?? '');
    final carTypeController = TextEditingController(text: contact?.carType ?? '');
    final vinController = TextEditingController(text: contact?.vin ?? '');

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(isEdit ? '编辑客户' : '添加客户'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '客户姓名',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(height: 16.h),
              TextField(
                controller: telController,
                decoration: const InputDecoration(
                  labelText: '手机号码',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.phone,
              ),
              SizedBox(height: 16.h),
              TextField(
                controller: carCodeController,
                decoration: const InputDecoration(
                  labelText: '车牌号码',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(height: 16.h),
              TextField(
                controller: carTypeController,
                decoration: const InputDecoration(
                  labelText: '车型',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(height: 16.h),
              TextField(
                controller: vinController,
                decoration: const InputDecoration(
                  labelText: '车架号',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          CommonButton(
            text: isEdit ? '保存' : '添加',
            onPressed: () async {
              if (nameController.text.isEmpty || telController.text.isEmpty) {
                showError('姓名和手机号不能为空');
                return;
              }

              Navigator.of(context).pop();
              await _saveContact(
                isEdit: isEdit,
                contact: contact,
                name: nameController.text,
                tel: telController.text,
                carCode: carCodeController.text,
                carType: carTypeController.text,
                vin: vinController.text,
              );
            },
          ),
        ],
      ),
    );
  }

  /// 保存客户信息
  Future<void> _saveContact({
    required bool isEdit,
    Contact? contact,
    required String name,
    required String tel,
    required String carCode,
    required String carType,
    required String vin,
  }) async {
    showLoading(isEdit ? '保存中...' : '添加中...');

    try {
      final appState = Provider.of<AppStateService>(context, listen: false);
      final newContact = Contact(
        id: isEdit ? contact!.id : null,
        carCode: carCode,
        name: name,
        tel: tel,
        carType: carType.isEmpty ? null : carType,
        owner: appState.currentUserTel,
        vin: vin.isEmpty ? null : vin,
      );

      final response = isEdit 
          ? await ApiService.updateContact(newContact)
          : await ApiService.addContact(newContact);

      if (response.isSuccess && response.data != null) {
        setState(() {
          if (isEdit) {
            final index = _contacts.indexWhere((c) => c.id == contact!.id);
            if (index != -1) {
              _contacts[index] = response.data!;
              _filteredContacts = List.from(_contacts);
            }
          } else {
            _contacts.add(response.data!);
            _filteredContacts = List.from(_contacts);
          }
        });

        // 更新应用状态
        if (isEdit) {
          appState.updateContact(response.data!);
        } else {
          appState.addContact(response.data!);
        }

        showSuccess(isEdit ? '保存成功' : '添加成功');
      } else {
        showError(response.message);
      }
    } catch (e) {
      showError('${isEdit ? '保存' : '添加'}失败: $e');
    } finally {
      hideLoading();
    }
  }

  @override
  PreferredSizeWidget? buildAppBar(BuildContext context) {
    return AppBar(
      title: _isSearching 
          ? TextField(
              controller: _searchController,
              decoration: const InputDecoration(
                hintText: '搜索客户...',
                border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.white70),
              ),
              style: const TextStyle(color: Colors.white),
              onChanged: _searchContacts,
              autofocus: true,
            )
          : const Text('客户管理'),
      backgroundColor: Colors.white,
      elevation: 0,
      actions: [
        IconButton(
          icon: Icon(_isSearching ? Icons.close : Icons.search),
          onPressed: () {
            setState(() {
              _isSearching = !_isSearching;
              if (!_isSearching) {
                _searchController.clear();
                _searchContacts('');
              }
            });
          },
        ),
        IconButton(
          icon: const Icon(Icons.add),
          onPressed: _addContact,
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 支持 AutomaticKeepAliveClientMixin，但忽略返回值
    return Scaffold(
      appBar: buildAppBar(context),
      body: LoadingOverlay(
        isLoading: isLoading,
        child: buildPageContent(context),
      ),
      floatingActionButton: buildFloatingActionButton(context),
      bottomNavigationBar: buildBottomNavigationBar(context),
      drawer: buildDrawer(context),
      endDrawer: buildEndDrawer(context),
    );
  }

  @override
  Widget buildPageContent(BuildContext context) {
    return Column(
      children: [
        // 统计信息
        Container(
          width: double.infinity,
          padding: EdgeInsets.all(16.w),
          margin: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: Colors.blue[50],
            borderRadius: BorderRadius.circular(8.r),
            border: Border.all(color: Colors.blue[200]!),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildStatItem('总客户', _contacts.length.toString(), Icons.people),
              _buildStatItem('今日新增', '0', Icons.add_circle),
            ],
          ),
        ),
        
        // 客户列表
        Expanded(
          child: _filteredContacts.isEmpty
              ? _buildEmptyState()
              : ListView.builder(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  itemCount: _filteredContacts.length,
                  itemBuilder: (context, index) {
                    final contact = _filteredContacts[index];
                    return _buildContactItem(contact);
                  },
                ),
        ),
      ],
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(icon, color: Colors.blue[600], size: 24.sp),
        SizedBox(height: 4.h),
        Text(
          value,
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
            color: Colors.blue[800],
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.blue[600],
          ),
        ),
      ],
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.people_outline,
            size: 64.sp,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16.h),
          Text(
            _isSearching ? '没有找到相关客户' : '暂无客户数据',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            _isSearching ? '尝试其他关键词' : '点击右上角"+"添加客户',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建客户列表项
  Widget _buildContactItem(Contact contact) {
    return Card(
      margin: EdgeInsets.only(bottom: 8.h),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: Colors.blue[100],
          child: Text(
            contact.name.isNotEmpty ? contact.name[0].toUpperCase() : '?',
            style: TextStyle(
              color: Colors.blue[800],
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        title: Text(
          contact.name,
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 4.h),
            Text(
              '手机: ${contact.tel}',
              style: TextStyle(fontSize: 14.sp, color: Colors.grey[600]),
            ),
            if (contact.carCode.isNotEmpty)
              Text(
                '车牌: ${contact.carCode}',
                style: TextStyle(fontSize: 14.sp, color: Colors.grey[600]),
              ),
            if (contact.carType != null && contact.carType!.isNotEmpty)
              Text(
                '车型: ${contact.carType}',
                style: TextStyle(fontSize: 14.sp, color: Colors.grey[600]),
              ),
          ],
        ),
        trailing: PopupMenuButton<String>(
          onSelected: (value) {
            switch (value) {
              case 'edit':
                _editContact(contact);
                break;
              case 'delete':
                _deleteContact(contact);
                break;
            }
          },
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'edit',
              child: Row(
                children: [
                  Icon(Icons.edit, size: 20),
                  SizedBox(width: 8),
                  Text('编辑'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'delete',
              child: Row(
                children: [
                  Icon(Icons.delete, size: 20, color: Colors.red),
                  SizedBox(width: 8),
                  Text('删除', style: TextStyle(color: Colors.red)),
                ],
              ),
            ),
          ],
        ),
        onTap: () {
          // 点击查看客户详情
          _showContactDetail(contact);
        },
      ),
    );
  }

  /// 显示客户详情
  void _showContactDetail(Contact contact) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(contact.name),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildDetailRow('手机号码', contact.tel),
              _buildDetailRow('车牌号码', contact.carCode),
              if (contact.carType != null && contact.carType!.isNotEmpty)
                _buildDetailRow('车型', contact.carType!),
              if (contact.vin != null && contact.vin!.isNotEmpty)
                _buildDetailRow('车架号', contact.vin!),
              if (contact.insertTime != null && contact.insertTime!.isNotEmpty)
                _buildDetailRow('添加时间', contact.insertTime!),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('关闭'),
          ),
          CommonButton(
            text: '编辑',
            onPressed: () {
              Navigator.of(context).pop();
              _editContact(contact);
            },
          ),
        ],
      ),
    );
  }

  /// 构建详情行
  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80.w,
            child: Text(
              '$label:',
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
                color: Colors.grey[700],
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: TextStyle(fontSize: 14.sp),
            ),
          ),
        ],
      ),
    );
  }
}
